<template>
	<div>
		<input type="text" v-model="name" placeholder="请输入搜索的歌曲">
		<button @click="searchMusic">搜索歌曲</button>
		<table>
			<tr>
				<th>编号</th>
				<th>歌曲名</th>
				<th>歌手</th>
				<th>操作</th>
			</tr>
			<audio style="display: none;" :src="url" autoplay controls>
				
			</audio>

			<tr v-for="song in list">
				<td>{{song.id}}</td>
				<td>{{song.name}}</td>
				<td>{{song.artists[0].name}}</td>
				<td>
					<button @click="play(song.id)">播放</button>
					<button @click="download(song.id,song.name)">下载</button>
				</td>
			</tr>
		</table>

	</div>
</template>

<script>
	export default {
		//通过Axios请求API https://v2.alapi.cn/api/music/search 获取请求响应的数据 渲染到页面上
		data() {
			return {
				list: null,
				name: '',
				url: ''
			}
		},
		methods: {
			searchMusic() {
				let url = "http://localhost:3000/search"
				this.$axios.get(url, {
					params: {
						//get请求的参数
						// token: "LwExDtUWhF3rH5ib",
						keywords: this.name,
						type:1
					}
				}).then(res => {
					console.log(res);
					this.list = res.data.result.songs
				})
				// let thiz = this
				// this.$axios.post(url, {
				// 	//POST请求的参数
				// 	token: "LwExDtUWhF3rH5ib",
				// 	keyword: this.name
				// }).then(function(res) {
				// 	thiz.list = res.data.data.songs
				// })
			},
			play(id){
				let url = "http://localhost:3000/song/url"
				this.$axios.get(url, {
					params: {
						//get请求的参数
						// token: "LwExDtUWhF3rH5ib",
						id: id
					}
				}).then(res => {
					console.log(res);
					this.url = res.data.data[0].url
				})
			},
			download(id,name){
				let url = "http://localhost:3000/song/url"
				this.$axios.get(url, {
					params: {
						//get请求的参数
						// token: "LwExDtUWhF3rH5ib",
						id: id
					}
				}).then(res => {
					let aEl = document.createElement("a")
					aEl.href = res.data.data[0].url+'?filename='+name
					aEl.download = res.data.data[0].url+'?filename='+name
					aEl.setAttribute("target","_blank") 
					aEl.click();
				})
			}
		}
	}
</script>

<style>
</style>
